<template>
	<view>
		<my-header>
			<uni-search-bar :radius="100" @confirm="searchNovel" @cancel="cancelSearch" @clear="cancelSearchValue" placeholder="请输入书名或作者"></uni-search-bar>
		</my-header>
		
		<view class="my-container">
			<!-- 搜索历史 -->
			<view v-if="isHistory">
				<view class="content-title">
					<view>搜索历史</view>
					<view @click="clearHistorys()">
						<uni-icons type="trash" size="24"></uni-icons>
					</view>
				</view>
				<view class="historys-box">
					<view class="history-item" v-for="(item, index) in historys" :key="index"  @click="searchHistory(item)">{{item}}</view>
				</view>
			</view>
			
			<!-- 搜索的小说列表 -->
			<view v-if="!isHistory">
				<!-- <view class="content-title">小说</view> -->
				<view v-show="showList" class="novel-list">
					<view class="novel-list-item" v-for="(novel,index) in novels" :key="index" @click="toNovelDetail(novel.id)">{{novel.name}}</view>
				</view>
				<view v-show="!showList">没有找到</view>
			</view>
		
		</view>
	</view>
</template>

<script>
	
	
	export default {
		data() {
			return {
				historys: [],
				isHistory: true,
				novels: [],
				showList: true
			}
		},
		methods: {
			// 跳转到小说详情
			toNovelDetail(id) {
				uni.navigateTo({
					url: './books-introduce?id=' + id
				})
			},
			
			// 取消搜索，回到上一页
			cancelSearch() {
				uni.navigateBack()
			},
			
			// 取消输入
			cancelSearchValue(e) {
				this.isHistory = true
			},
			// 从搜索历史搜索
			searchHistory(novel) {
				this.sendApi(novel)
			},
			
			// 搜索
			searchNovel(e) {
				this.historys.push(e.value)
				this.sendApi(e.value)
			},
			sendApi(value) {
				this.myApi({
					url: '/api/searchnovel',
					domain: true,
					data: {searchValue: value}
				}).then((res)=>{
					this.isHistory = false
					if(res.status == 10010) {
						this.showList = false
					} else {
						this.showList = true
						this.novels = res.data
					}
				})
			},
			
			// 清除历史
			clearHistorys() {
				this.historys = []
				uni.removeStorageSync('historys')
			}
		},
		onLoad() {
			this.historys = uni.getStorageSync('historys') ? uni.getStorageSync('historys') : []
		},
		beforeDestroy() {
			if(this.historys) uni.setStorageSync('historys', this.historys)
		}
		
	}
</script>

<style>
	.header-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		text-align: center;
	}
	
	.historys-box {
		display: flex;
		justify-content: left;
		align-items: center;
		text-align: center;
		flex-wrap: wrap;
	}
	
	.history-item {
		/* width: 25%; */
		border: 1px solid #CCEED0;
		border-radius: 40rpx;
		padding: 10rpx 20rpx;
		margin-right: 30rpx;
		margin-bottom: 30rpx;
	}
	
/* 	.historys-container, .novel-container {
		padding: 0 30rpx;
	} */
	
	.content-title {
		font-size: 30rpx;
		padding: 20rpx 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		text-align: center;
	}
	
	.novel-list {
		
	}
	
	.novel-list-item {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #ccc;
	}
</style>
